//
//  LLUrlViewController.swift
//  新印象
//
//  Created by wyl on 2016/12/20.
//  Copyright © 2016年 魏延龙. All rights reserved.
//

import UIKit
import WebKit


class LLUrlViewController: UIViewController,WKNavigationDelegate {

    var url : String!
    var wk : WKWebView!
    var progress : UIProgressView!
    override func viewDidLoad() {
        super.viewDidLoad()
        loadUI()
    }

    func loadUI() {
        
        progress = UIProgressView()
        progress.tintColor = .blue
        progress.trackTintColor = .white
        self.view.addSubview(progress)
        progress.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.equalTo(self.view)
            make.height.equalTo(2)
        }
        
        wk = WKWebView()
        wk.load(URLRequest(url: URL(string: url)!))
        wk.navigationDelegate = self
        wk.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.init(rawValue: NSKeyValueObservingOptions.new.rawValue | NSKeyValueObservingOptions.old.rawValue) , context: nil)
        self.view.addSubview(wk)
        wk.snp.makeConstraints { (make) in
            make.top.equalTo(progress.snp.bottom).offset(0)
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(44)
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            let pro = change?[.newKey] as! Float
            progress .setProgress(pro, animated: true)
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        progress.isHidden = true
        wk.snp.remakeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(44)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    deinit {
        wk.removeObserver(self, forKeyPath: "estimatedProgress")
    }
}
